<?php
declare (strict_types=1);

namespace app\admin\controller;

use Exception;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;


/**
 * @note    管理员
 * @author  liujian
 * Class Admin
 * @package app\admin\controller
 * @Create  Date : 2021年04月01日 下午1:57:18
 */
class Admin extends Base
{
    /**
     * @OA\Get(path="/admin/list",
     *   tags={"管理员管理"},
     *   summary="管理员列表",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="page_size", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Parameter(name="search", in="query", description="关键词", @OA\Schema(type="string", default="")),
     *   @OA\Parameter(name="start_time", in="query", description="开始时间", @OA\Schema(type="string", default="")),
     *   @OA\Parameter(name="end_time", in="query", description="结束时间", @OA\Schema(type="string", default="")),
     *   @OA\Parameter(name="status", in="query", description="状态 1正常 2冻结 0所有", @OA\Schema(type="int", default="0")),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *               @OA\Property(property="list", type="object",description="列表"),
     *          ),
     *      ),
     *   ),
     * )
     */
    public function list(int $pageSize = 10)
    {
        $where_search = "";
        $where = [];

        if (!empty(input("search"))) {
            $where_search = 'name like "%' . input("search") . '%"';
            $where_search .= ' or realname like "%' . input("search") . '%"';
        }
        if (input("status")) {
            $where[] = ['status', '=', input("status")];
        }
        if (!empty(input("start_time")) && !empty(input("end_time"))) {
            $where[] = ['create_time', '<', input("end_time")];
            $where[] = ['create_time', '>', input("start_time")];
        }
        //
        $list = Db::name("admin")
            ->where($where_search)
            ->where($where)
            ->order("id")
            ->paginate($pageSize);
        return $this->jsonSuccessData("获取成功", [
            "list" => $list
        ]);
    }


    /**
     * @OA\Post(path="/admin/save",
     *   tags={"管理员管理"},
     *   summary="管理员添加/修改",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="id", property="ID", type="int", default=""),
     *           @OA\Property(description="账号", property="name", type="string", default=""),
     *           @OA\Property(description="密码", property="password", type="string", default=""),
     *           @OA\Property(description="真实昵称", property="realname", type="string", default=""),
     *           @OA\Property(description="状态 1正常 2冻结", property="status", type="int", default="1"),
     *           required={"name", "password", "realname", "status" , "role_ids"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *          ),
     *      ),
     *   ),
     * )
     */
    public function save(Request $request, int $id = 0)
    {
        try {
            $token = trim(Request::header('token'));
            $admin_info = Cache::store('redis')->get('admin_' . $token);

            if ($id == 1 && $admin_info['id'] != 1) {
                throw new Exception("超级管理员不能被操作");
            }
            $update_data = array(
                'name'        => input('name'),
                'realname'    => input('realname'),
                'status'      => input('status'),
                'update_time' => date("Y-m-d H:i:s")
            );
            if (!empty(input('pwd'))) {
                $update_data['pwd'] = md5(input('pwd'));
            }
            if ($id) {
                $info = Db::name("admin")->where('name', input('name'))->where("id", '<>', $id)->find();
                if (!empty($info)) throw new Exception("已存在该管理员");

                Db::name("admin_role")->where("admin_id", $id)->delete();

                //
                $res = Db::name("admin")->where('id', $id)->update($update_data);
                if (!$res) throw new Exception("操作失败");
                addAdminLog("修改管理员" . input('name') . '信息为' . json_encode($update_data), '添加管理员');
            } else {
                $info = Db::name("admin")->where('name', input('name'))->find();
                if (!empty($info)) throw new Exception("已存在该管理员");
                $update_data['create_time'] = date("Y-m-d H:i:s");
                //
                $res = Db::name("admin")->insert($update_data);
                if (!$res) throw new Exception("操作失败");
                $id = Db::name("role")->getLastInsID();
                addAdminLog("添加管理员" . input('name') . '信息为' . json_encode($update_data), '添加管理员');
            }

            if (!empty(input("role_ids"))) {
                $role_ids = explode(",", input("role_ids"));
                $insert_list = [];
                for ($i = 0; $i < count($role_ids); $i++) {
                    $insert_list[] = ['admin_id' => $id, 'role_id' => $role_ids[$i]];
                }
                // 添加管理员权限表
                $res = Db::name("admin_role")->insertAll($insert_list);
                if (!$res) throw new Exception("操作失败");
            }

            return $this->jsonSuccessData("操作成功");
        } catch (Exception $e) {
            return $this->jsonFailData($e->getMessage());
        }
    }

    /**
     * @OA\Post(path="/admin/update_status",
     *   tags={"管理员管理"},
     *   summary="管理员冻结/启用",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="ID", property="id", type="int", default=""),
     *           @OA\Property(description="状态 1正常 2冻结", property="status", type="int", default="1"),
     *           required={"id", "status"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *          ),
     *      ),
     *   ),
     * )
     */
    public function update_status(int $id = 0, int $status = 0)
    {
        if ($id == 1)
            throw new ValidateException('超级管理员不能被操作');

        if ($id) {
            $update_data = array(
                'status'      => $status,
                'update_time' => date("Y-m-d H:i:s")
            );
            //
            $res = Db::name("admin")->where('id', $id)->update($update_data);
            if (!$res) throw new Exception("操作失败");;
        }
        return $this->jsonSuccessData("操作成功");
    }

    /**
     * @OA\Post(path="/admin/delete",
     *   tags={"管理员管理"},
     *   summary="管理员删除",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="ID", property="id", type="int", default=""),
     *           required={"id"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *          ),
     *      ),
     *   ),
     * )
     */
    public function delete($id)
    {
        if ($id == 1)
            throw new ValidateException('超级管理员不能被操作');

        //
        $res = Db::name("admin")->where('id', 'in', $id)->delete();
        if ($res) {
            // 删除管理员权限表
            Db::name("admin_role")->where("admin_id", 'in', $id)->delete();
            addAdminLog("删除管理员$id", '删除管理员');
            return $this->jsonSuccessData("操作成功");
        } else {
            return $this->jsonFailData("操作失败");
        }
    }

    /**
     * @OA\Get(path="/admin/read",
     *   tags={"管理员管理"},
     *   summary="管理员详情",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *   @OA\Parameter(name="id", in="query", description="ID", @OA\Schema(type="int", default="1")),
     *   @OA\Response(
     *       response=200,
     *       description="The Member",
     *       @OA\JsonContent(type="object",
     *           @OA\Property(property="msg", type="string"),
     *           @OA\Property(property="code", type="integer", default="200"),
     *           @OA\Property(property="data", type="object",
     *               @OA\Property(property="id", type="integer", description="ID"),
     *               @OA\Property(property="name", type="string", description="账号"),
     *               @OA\Property(property="password", type="string", description="密码"),
     *               @OA\Property(property="realname", type="integer", description="真实昵称"),
     *               @OA\Property(property="status", type="integer", description="用户状态 1正常 2冻结"),
     *               @OA\Property(property="update_time", type="string", description="更新时间"),
     *               @OA\Property(property="create_time", type="string", description="创建时间"),
     *           ),
     *       ),
     *    ),
     * )
     */
    public function read($id)
    {
        //
        $info = Db::name("admin")->where('id', $id)->find();
        // 获取管理员
        $role_list = Db::name("admin_role")
            ->alias('admin_role')
            ->field("admin_role.*,role.name as role_name")
            ->leftJoin("think_role role", "role.id=admin_role.role_id")
            ->where("admin_id", $id)
            ->select()->toArray();
        return $this->jsonSuccessData("操作成功", [
            'info'      => $info,
            'role_list' => $role_list
        ]);
    }
}
